﻿using System.Reflection.Emit;
using System.Text;
using rpc_service.cache;

namespace rpc_service.core.support.assembly.il;

public class ILUtil
{
    protected void appendStringBuilder(ILGenerator il, LocalBuilder stringBuilderLocal, string str)
    {
        il.Emit(OpCodes.Ldloc, stringBuilderLocal);
        il.Emit(OpCodes.Ldstr, str);
        il.Emit(OpCodes.Callvirt, "StringBuilder".GetTypeByStr().GetMethod("Append", new[] { "string".GetTypeByStr() })!);
        il.Emit(OpCodes.Stloc, stringBuilderLocal);
    }
    
    protected void appendStringBuilder(ILGenerator il, LocalBuilder stringBuilderLocal, int index, Type type)
    {
        il.Emit(OpCodes.Ldloc, stringBuilderLocal);
        il.Emit(OpCodes.Ldarg, index); // 加载参数值
        if (type.IsValueType)
        {
            il.Emit(OpCodes.Box, type); // 如果是值类型，则装箱。栈: [stringBuilder, boxedArgValue]
        }
        //    ToString() 的结果（一个字符串）将替换栈顶的对象。
        il.Emit(OpCodes.Callvirt, "object".GetTypeByStr().GetMethod("ToString", System.Type.EmptyTypes)!);
        il.Emit(OpCodes.Callvirt, "StringBuilder".GetTypeByStr().GetMethod("Append", new[] { "string".GetTypeByStr() })!);
        il.Emit(OpCodes.Stloc, stringBuilderLocal);
    }
}